<?php
// security_lib.php - 安全函数库
class UltimateShield {
    const MAX_LENGTH = 2000;
    
    public static function initSession() {
        // 安全启动会话（仅启动一次）
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_set_cookie_params([
                'lifetime' => 86400,
                'path' => '/',
                'domain' => $_SERVER['HTTP_HOST'],
                'secure' => isset($_SERVER['HTTPS']),
                'httponly' => true,
                'samesite' => 'Strict'
            ]);
            @session_start();
        }
    }
    
    public static function getSession($key, $default = '') {
        return isset($_SESSION[$key]) ? self::sanitize($_SESSION[$key]) : $default;
    }
    
    public static function sanitize($input) {
        if (is_array($input)) {
            return array_map([__CLASS__, 'sanitize'], $input);
        }
        
        if (!is_string($input)) {
            return $input;
        }
        
        // 长度控制
        if (strlen($input) > self::MAX_LENGTH) {
            $input = substr($input, 0, self::MAX_LENGTH);
        }
        
        // 移除非打印字符
        $input = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $input);
        
        // 基础过滤
        return htmlspecialchars($input, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    }
    
    public static function display($content) {
        return self::sanitize($content);
    }
    
    // SQL安全函数
    public static function sqlSafe($pdo, $sql, $params = []) {
        $stmt = $pdo->prepare($sql);
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, self::sanitize($value), PDO::PARAM_STR);
        }
        $stmt->execute();
        return $stmt;
    }
}

// 安全响应头配置
function setSecurityHeaders() {
    header("Content-Security-Policy: default-src 'self'; script-src 'none'; object-src 'none'");
    header("X-Content-Type-Options: nosniff");
    header("X-Frame-Options: DENY");
    header("Referrer-Policy: no-referrer");
}